var Table = pi.base.extend({
    "$Init":function(){
        this.element.setHighlight([]).environment.setKing([]);
        var reverse = Array.prototype.indexOf.call(arguments,Table.REVERSE)>-1,
        lnumbers = reverse&&"1 2 3 4 5 6 7 8"||"8 7 6 5 4 3 2 1",
        cletters = "abcdefgh";
        main.engine.element.getFooter().element.parentNode.pi.remove();
        this.element.setContainer( new pi.element("div").attribute.addClass("Table").insert(main.engine.element.getMiddle().update("")) );
        this.element.setStatus( new pi.element("div").attribute.addClass("ButtonBorder StatusContent").update(main.text.initializingBoard).insert(new pi.element("div").attribute.addClass("Status Button").insert(this.element.getContainer())) );
        
        new pi.element("img").attribute.set("src","/static/img/Gnome-application-exit.png").attribute.addClass("LeaveButton").event.addListener("click",Table.Leave).insert( this.element.getContainer() );
        
        this.element.getContainer().child.add(
          new pi.element("div").attribute.addClass("Numbering Left").update(lnumbers),
          new pi.element("div").attribute.addClass("Numbering Right").update(lnumbers),
          new pi.element("div").attribute.addClass("Numbering Top").update(cletters),
          new pi.element("div").attribute.addClass("Numbering Bottom").update(cletters)
        );
        this.element.setBoard( 
          new pi.element("div").attribute.addClass("Board "+(reverse&&"BlackBoard"||"")).insert(this.element.getContainer()) 
        );
        this.element.setMonitor( new pi.element("div").attribute.addClass("Monitor").insert(this.element.getContainer()) );
        
        this.element.getMonitor().child.add(
          new pi.element("h3").attribute.addClass("Title").update(main.text.opponent),
          this.element.setOpponent(new pi.element("div").update(main.text.waitingForOpponent)).element.getOpponent()
        );
   
        this.element.getMonitor().child.add(
            new pi.element("h3").attribute.addClass("Title").update(main.text.moveList)
        );
        
        new pi.element("div").attribute.addClass("MoveList").child.add(
          this.element.setWhiteMoveList( new pi.element("div").attribute.addClass("White").child.add(new pi.element("strong").update(main.text.white)) ).element.getWhiteMoveList(),
          this.element.setBlackMoveList( new pi.element("div").attribute.addClass("Black").child.add(new pi.element("strong").update(main.text.black)) ).element.getBlackMoveList()
        ).insert(this.element.getMonitor());
        
        for(var i=0; i<8; i++){
            this.environment.getMap()[i] = [];
            for(var t=0; t<8; t++){
                this.environment.getMap()[i][t] = new Square(i,t);
            }
        };

        return this;
    },
    "close":function(_winner){
        var message = main.text[(_winner==this.environment.getUser().environment.getColor()&&"won"||"lost")];
        alert(
          message
        );
        this.environment.setStatusText(message);
        this.environment.setNext(null);
    },
    "highlight":function(_cell,_piece){
        for(var i=0, len=_cell.length; i<len; i++){
            var cell = _cell[i];
            this.element.getHighlight().push(
                new pi.element("div").attribute.addClass("Highlight").addStyle({ "left":cell.getLeft(_piece)+"px", "top":cell.getTop(_piece)+"px" }).
                event.addListener("click",Piece.Move.curry(window,_piece,cell)).
                event.addListener("click",_piece.blur.curry(_piece)).
                insert(this.element.getBoard())
            );
        }
    },
    "setup":function(_data){
        for(var id in _data){
            var obj = new window[_data[id].value<6?"Piece":"King"](
              id,_data[id].user,_data[id].color,_data[id].value,
              new pi.element("div").insert(this.element.getBoard())
            );
            obj.environment.getElement().attribute.set("id","piece"+id).event.addListener("click",obj.focus.curry(obj));
            obj.move(_data[id].x,_data[id].y);
            obj.environment.setServerTime(_data[id].time);
            this.environment.setServerTime(Math.max(this.environment.getServerTime(),_data[id].time));
            this.environment.getPiece()[id] = obj;
        }
        this.environment.setNext(
          this.environment.getUser().environment.getColor()!=obj.environment.getColor()?
          this.environment.getUser():
          this.environment.getOpponent()
        );
        console.log( "User color:", this.environment.getUser().environment.getColor() );
        this.environment.setStatusText(main.text[
          this.environment.getUser().environment.getColor()==0?"waitingForOpponent":"waitingOpponentsMove"
        ],'Blue');
        this.environment.setIsInitialized(true);
    },
    "listenMove":function(_piecesMoved){
      main.engine.environment.getActiveServer().environment.setIsLocked(false);
      if(Boolean(_piecesMoved)){
        console.log("||| Some moved piece data was got:",_piecesMoved," |||");
        for(var id in _piecesMoved){
          var piece = this.environment.getPiece()[id];
          piece.move(_piecesMoved[id].x,_piecesMoved[id].y);
          piece.environment.setServerTime(_piecesMoved[id].time);
          this.environment.setServerTime(Math.max(this.environment.getServerTime(),_piecesMoved[id].time));
        }
        this.environment.setNext(
          piece.environment.getColor()!=this.environment.getUser().environment.getColor()?
          this.environment.getUser():
          this.environment.getOpponent()
        );
        var isNext = piece.environment.getColor()!=this.environment.getUser().environment.getColor();
        this.environment.setStatusText(
          main.text[
            isNext&&"yourMove"||"waitingOpponentsMove"
          ],
          isNext&&"Green"||"Blue"
        );
      } else {
        main.engine.environment.getActiveServer().listen.move();
      }
    },
    "listenOpponent":function(_opponent){
      if(_opponent==null){
        main.engine.environment.getActiveServer().environment.setIsLocked(false);
        main.engine.environment.getActiveServer().listen.opponent();
      } else
        this.environment.setOpponent(_opponent);
    },
    "element":{ 
        "_board":null, "_container":null, "_highlight":null, "_monitor":null, "_whiteMoveList":null, "_blackMoveList":null, "_opponent":null, "_userList":null, "_status":null
    },
    "environment":{
        "_activePiece":null, "_opponent":null, "_id":0, "_isInitialized":false, "_king":null, "_map":[], "_next":null, "_nickname":"", "_user":null, "_piece":{}, "_rook":true, "_serverTime":0, "_statusText":"", "_time":0,
        "setServerTime":function(_value){
          console.log("===> setting servertime: ",_value);
          this._setServerTime(_value);
        },
        "setStatusText":function(_value,_class){
          this._parent_.element.getStatus().update(_value);
          this._parent_.element.getStatus().element.parentNode.pi.attribute.setClass("Button Status "+(_class||""));
          this._setStatusText(_value);
        },
        "setOpponent":function(_value){
          if(this.getUser().environment.getColor()==0){
            main.engine.environment.getActiveServer().disconnect();
          }
          this._parent_.element.getOpponent().update("\
            <strong>Name: </strong> %(name)<br /> \
            <strong>Location: </strong> %(location)<br /> \
            <strong>Registered?: </strong> %(isRegistered) \
          ".format({ 
            "name":_value.environment.getName(),
            "location":_value.environment.getLocation(),
            "isRegistered":(_value.environment.getIsRegistered() && "Yes" || "No"),
            "gamesPlayed":_value.environment.getGamesPlayed(),
            "gamesWon":_value.environment.getGamesWon()
          }));
          this._setOpponent(_value);
          if(this._parent_.environment.getNext()!=this._parent_.environment.getUser()){
            this.setStatusText(main.text.waitingOpponentsMove,'Blue');
            this._parent_.listenMove(null);
          } else
            this.setStatusText(main.text.yourMove,'Green');
        }
    }
});
Table.FixVerticalDirection = function(_square,_piece){
    return (
        main.engine.environment.getTable().environment.getUser().environment.getColor()==0?
            Math.abs(_square.environment.getY()-7)
        :
            _square.environment.getY()
    )
};
Table.Leave = function(){
  main.engine.environment.getActiveServer().disconnect();
  main.engine.element.getContainer().remove();
  main.engine.createMainScreen();
  main.engine.environment.setTable(null);
  main.engine.environment.getActiveServer().listen.table();
}

Table.REVERSE = new Object;
